<?php

namespace backend\modules\home\controllers;

use common\components\Tools;
use Yii;
use backend\modules\home\models\Booklist;
use backend\modules\home\models\BooklistImg;
use backend\modules\home\models\BooklistSearch;
use common\components\Upload;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * BookController implements the CRUD actions for Booklist model.
 */
class BookController extends Controller
{
    /**
     * @inheritdoc
     */
    public $enableCsrfValidation = false;
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Booklist models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new BooklistSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Booklist model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Booklist model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Booklist();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {

            if($model->parent_id != 0){
               $parent =  Booklist::find()->where(['id' => $model->parent_id])->one();
               if($parent){
                   $parent->update_at = time();
                   $parent->save();
               }
            }


            return $this->redirect(['view', 'id' => $model->id]);
        }
        $catelist = Tools::getTopCate();

        // 父目录

        $parentlist = Booklist::find()
            ->select('backend_title,id')
            ->where(['parent_id' => 0, 'is_over' => 0])
            ->orderBy([
                'sort' => SORT_DESC,
                'id' => SORT_ASC,])
            ->indexBy('id')
            ->column();
        $parentlist[0] = '无上级目录';
        ksort($parentlist);

        return $this->render('create', [
            'model' => $model,
            'catelist' => $catelist,
            'parentlist' => $parentlist,
        ]);
    }

    /**
     * Updates an existing Booklist model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }
//        echo "<pre>";
//        print_r($model);
        $catelist = Tools::getTopCate();

        // 父目录

        $parentlist = Booklist::find()
            ->select('backend_title,id')
            ->where(['parent_id' => 0])
            ->orderBy([
                'sort' => SORT_DESC,
                'id' => SORT_ASC,])
            ->indexBy('id')
            ->column();
        $parentlist[0] = '无上级目录';
        ksort($parentlist);
//        echo "<pre>";
//        print_r($parentlist);exit;
        return $this->render('update', [
            'model' => $model,
            'catelist' => $catelist,
            'parentlist' => $parentlist,
        ]);
    }

    public function actionUpload($id)
    {
        $model = $this->findModel($id);
        if (Yii::$app->request->isPost) {

            $res = (new Upload)->uploadfile($model->number);
            if($res['code'] == 200){
                $img_model = new BooklistImg();
                $img_model->title = $res['title'];
                $img_model->number_code = $model->number;
                $img_model->path = $res['data'];
                $img_model->type = 0;
                $img_model->sort = 0;
                $img_model->create_at = time();
                if(!$img_model->save()){
                    echo "<pre>";
                    print_r($img_model->errors);exit;
                }
            }
        }

        return $this->render('upload', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Deletes an existing Booklist model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     * @throws \Throwable
     * @throws \yii\db\StaleObjectException
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    public function actionSetCoverPhoto($id){
        $model = BooklistImg::findOne($id);
        $item_model = Booklist::find()->where(['number' => $model->number_code])->one();
        if($model && $item_model){
            if($model->type != 1){
                $model->type = 1;
                if($model->save()){
                    // 更新封面地址
                    $item_model->thumb_img = $model->path;
                    if(!$item_model->save()){
                        echo "<pre>";
                        print_r($item_model->errors);exit;
                    }
                }
            }else{
                $model->type = 0;
                if($model->save()){
                    // 更新封面地址
                    $item_model->thumb_img = '';
                    if(!$item_model->save()){
                        echo "<pre>";
                        print_r($item_model->errors);exit;
                    }
                }
            }
            return $this->redirect(['view', 'id' => $item_model->id]);
        }else{
            echo 'error';exit;
        }


    }

    public function actionDeletePhoto($id){
        $model = BooklistImg::findOne($id);
        $item_model = Booklist::find()->where(['number' => $model->number_code])->one();
        if($model && $item_model){
            $number = $model->number_code;
            if($model->type == 1){
                echo "<script>alert('先取消封面再删除');window.history.go(-1)</script>";exit;
            }
            @unlink(getcwd().$model->path);
            $model->delete();
            return $this->redirect(['view', 'id' => $item_model->id]);

        }else{
            echo 'error';exit;
        }
    }

    public function actionSetPhotoSort($id){
        $model = BooklistImg::findOne($id);
        if($model->sort == 1){
            $model->sort = 0;
        }else{
            $model->sort = 1;
        }
        $model->save();
        echo "<script>window.history.go(-1)</script>";exit;
    }

    public function actionUploadCover($id){
        $model = $this->findModel($id);
        if (Yii::$app->request->isPost) {
            if($model->thumb_img){
                @unlink(getcwd().$model->thumb_img);
            }
            $res = (new Upload)->uploadfile($model->number);
            if($res['code'] == 200){
                $model->thumb_img = $res['data'];
                $model->save();
            }
        }

        return $this->render('upload', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Finds the Booklist model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Booklist the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Booklist::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
